<template>
  <div class="credits-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>积分管理</h1>
      <p>管理积分套餐、交易记录和消耗规则</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" :xs="12">
        <div class="data-card">
          <div class="value">{{ formatNumber(stats.totalCredits) }}</div>
          <div class="label">积分总发放</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card success">
          <div class="value">{{ formatNumber(stats.totalConsumed) }}</div>
          <div class="label">积分总消耗</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card warning">
          <div class="value">{{ formatNumber(stats.totalOrders) }}</div>
          <div class="label">购买订单数</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card info">
          <div class="value">¥{{ formatNumber(stats.totalRevenue) }}</div>
          <div class="label">积分收入</div>
        </div>
      </el-col>
    </el-row>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <!-- 积分套餐管理 -->
      <el-tab-pane label="积分套餐" name="packages">
        <div class="content-card">
          <div class="toolbar">
            <h3>积分套餐管理</h3>
            <div class="toolbar-buttons">
              <el-button type="primary" @click="handleAddPackage">
                <el-icon><Plus /></el-icon>
                新增套餐
              </el-button>
              <el-button type="success" @click="handleSyncPackagesToMiniProgram">
                <el-icon><Refresh /></el-icon>
                同步小程序数据库
              </el-button>
            </div>
          </div>

          <el-table :data="packageList" :loading="packagesLoading" stripe style="width: 100%">
            <el-table-column prop="id" label="套餐ID" width="80" />
            <el-table-column prop="name" label="套餐名称" width="150" />
            <el-table-column prop="creditsAmount" label="积分数量" width="120">
              <template #default="scope">
                <span class="credits-amount">{{ formatNumber(scope.row.creditsAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="price" label="售价" width="100">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="originalPrice" label="原价" width="100">
              <template #default="scope">
                <span v-if="scope.row.originalPrice">¥{{ scope.row.originalPrice }}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column prop="discountLabel" label="标签" width="100">
              <template #default="scope">
                <el-tag v-if="scope.row.discountLabel" type="warning" size="small">
                  {{ scope.row.discountLabel }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isPopular" label="热门推荐" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.isPopular ? 'success' : 'info'" size="small">
                  {{ scope.row.isPopular ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="validityDays" label="有效期" width="100">
              <template #default="scope">
                {{ scope.row.validityDays }}天
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEditPackage(scope.row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status === 1 ? 'danger' : 'success'"
                  @click="handleTogglePackageStatus(scope.row)"
                >
                  {{ scope.row.status === 1 ? '下架' : '上架' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>

      <!-- 交易记录 -->
      <el-tab-pane label="交易记录" name="transactions">
        <div class="content-card">
          <div class="toolbar">
            <el-form :model="transactionSearch" class="search-form" inline>
              <el-form-item label="用户ID">
                <el-input v-model="transactionSearch.userId" placeholder="请输入用户ID" clearable />
              </el-form-item>
              <el-form-item label="交易类型">
                <el-select v-model="transactionSearch.transactionType" placeholder="请选择类型" clearable>
                  <el-option label="购买" value="purchase" />
                  <el-option label="消费" value="consume" />
                  <el-option label="获得" value="earn" />
                  <el-option label="退款" value="refund" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearchTransactions">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleResetTransactions">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <el-table :data="transactionList" :loading="transactionsLoading" stripe style="width: 100%">
            <el-table-column prop="id" label="交易ID" width="120" />
            <el-table-column prop="userId" label="用户ID" width="80" />
            <el-table-column prop="transactionType" label="交易类型" width="100">
              <template #default="scope">
                <el-tag :type="getTransactionTypeColor(scope.row.transactionType)" size="small">
                  {{ getTransactionTypeText(scope.row.transactionType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="积分变动" width="120">
              <template #default="scope">
                <span :class="scope.row.amount > 0 ? 'amount-positive' : 'amount-negative'">
                  {{ scope.row.amount > 0 ? '+' : '' }}{{ formatNumber(scope.row.amount) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="balanceBefore" label="变动前余额" width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.balanceBefore) }}
              </template>
            </el-table-column>
            <el-table-column prop="balanceAfter" label="变动后余额" width="120">
              <template #default="scope">
                {{ formatNumber(scope.row.balanceAfter) }}
              </template>
            </el-table-column>
            <el-table-column prop="sourceType" label="来源" width="120">
              <template #default="scope">
                {{ getSourceTypeText(scope.row.sourceType) }}
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述" min-width="200" />
            <el-table-column prop="createTime" label="时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-model:current-page="transactionPagination.page"
            v-model:page-size="transactionPagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="transactionPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleTransactionSizeChange"
            @current-change="handleTransactionCurrentChange"
            class="pagination"
          />
        </div>
      </el-tab-pane>

      <!-- 消耗规则 -->
      <el-tab-pane label="消耗规则" name="rules">
        <div class="content-card">
          <div class="toolbar">
            <h3>积分消耗规则</h3>
            <div class="toolbar-buttons">
              <el-button type="primary" @click="handleAddRule">
                <el-icon><Plus /></el-icon>
                新增规则
              </el-button>
              <el-button type="success" @click="handleSyncRulesToMiniProgram">
                <el-icon><Refresh /></el-icon>
                同步小程序数据库
              </el-button>
            </div>
          </div>

          <el-table :data="ruleList" :loading="rulesLoading" stripe style="width: 100%">
            <el-table-column prop="type" label="功能类型" width="150" />
            <el-table-column prop="name" label="功能名称" width="150" />
            <el-table-column prop="cost" label="消耗积分" width="120">
              <template #default="scope">
                <span class="credits-amount">{{ scope.row.cost }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="unit" label="单位" width="120" />
            <el-table-column prop="description" label="描述" min-width="200" />
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button size="small" @click="handleEditRule(scope.row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  :type="scope.row.status === 1 ? 'danger' : 'success'"
                  @click="handleToggleRuleStatus(scope.row)"
                >
                  {{ scope.row.status === 1 ? '禁用' : '启用' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 套餐编辑弹窗 -->
    <el-dialog v-model="packageDialogVisible" :title="packageForm.id ? '编辑套餐' : '新增套餐'" width="600px">
      <el-form :model="packageForm" :rules="packageRules" ref="packageFormRef" label-width="100px">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="packageForm.name" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="积分数量" prop="creditsAmount">
          <el-input-number v-model="packageForm.creditsAmount" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input-number v-model="packageForm.price" :min="0.01" :precision="2" controls-position="right" />
        </el-form-item>
        <el-form-item label="原价">
          <el-input-number v-model="packageForm.originalPrice" :min="0.01" :precision="2" controls-position="right" />
        </el-form-item>
        <el-form-item label="折扣标签">
          <el-input v-model="packageForm.discountLabel" placeholder="如：最划算、超值等" />
        </el-form-item>
        <el-form-item label="热门推荐">
          <el-switch v-model="packageForm.isPopular" />
        </el-form-item>
        <el-form-item label="有效期(天)" prop="validityDays">
          <el-input-number v-model="packageForm.validityDays" :min="1" controls-position="right" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="packageForm.status">
            <el-radio :value="1">上架</el-radio>
            <el-radio :value="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="packageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePackage" :loading="packageSubmitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus, Refresh, Edit, Search } from '@element-plus/icons-vue'
import { 
  getCreditsStats, 
  getCreditsPackages, 
  getCreditsTransactions, 
  getCreditsRules,
  createCreditsPackage,
  updateCreditsPackage,
  updateCreditsPackageStatus,
  createCreditsRule,
  updateCreditsRule,
  updateCreditsRuleStatus,
  syncCreditsPackagesToMiniProgram,
  syncCreditsRulesToMiniProgram
} from '@/api'

// 响应式数据
const activeTab = ref('packages')
const packagesLoading = ref(false)
const transactionsLoading = ref(false)
const rulesLoading = ref(false)
const packageDialogVisible = ref(false)
const packageSubmitting = ref(false)

// 统计数据
const stats = ref({
  totalCredits: 0,
  totalConsumed: 0,
  totalOrders: 0,
  totalRevenue: 0
})

// 套餐列表
const packageList = ref<any[]>([])
const packageFormRef = ref<FormInstance>()

// 交易记录
const transactionList = ref<any[]>([])
const transactionPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 消耗规则
const ruleList = ref<any[]>([])

// 搜索表单
const transactionSearch = reactive({
  userId: '',
  transactionType: ''
})

// 套餐表单
const packageForm = reactive({
  id: null,
  name: '',
  creditsAmount: 0,
  price: 0,
  originalPrice: 0,
  discountLabel: '',
  isPopular: false,
  validityDays: 730,
  status: 1
})

// 表单验证规则
const packageRules = {
  name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
  creditsAmount: [{ required: true, message: '请输入积分数量', trigger: 'blur' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  validityDays: [{ required: true, message: '请输入有效期', trigger: 'blur' }]
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await getCreditsStats()
    if (response && response.success) {
      stats.value = {
        totalCredits: response.data.totalCredits || 0,
        totalConsumed: response.data.totalConsumed || 0,
        totalOrders: response.data.totalOrders || 0,
        totalRevenue: response.data.totalRevenue || 0
      }
    }
  } catch (error) {
    console.error('加载积分统计失败:', error)
  }
}

// 加载套餐列表
const loadPackageList = async () => {
  packagesLoading.value = true
  try {
    console.log('🔍 [前端调试] 开始调用管理端积分套餐API...')
    console.log('🔍 [前端调试] 当前时间戳:', new Date().toISOString())
    console.log('🔍 [前端调试] 当前URL:', window.location.href)
    console.log('🔍 [前端调试] 预期API路径: /api/admin/credits/packages')
    
    const response = await getCreditsPackages()
    
    console.log('📡 [前端调试] API响应完整内容:', JSON.stringify(response, null, 2))
    console.log('📡 [前端调试] 响应状态:', response?.status)
    console.log('📡 [前端调试] 响应成功标志:', response?.success)
    console.log('📡 [前端调试] 响应数据长度:', response?.data?.length)
    
    if (response && response.success) {
      packageList.value = response.data || []
      console.log('✅ [前端调试] 套餐列表加载成功，共', packageList.value.length, '个套餐')
      console.log('✅ [前端调试] 第一个套餐详情:', packageList.value[0])
    } else {
      console.error('❌ [前端调试] 加载失败，响应消息:', response?.message)
      ElMessage.error('加载积分套餐失败')
    }
  } catch (error: any) {
    console.error('❌ [前端调试] 异常信息:', error)
    console.error('❌ [前端调试] 错误消息:', error.message)
    console.error('❌ [前端调试] 网络状态:', error.response?.status)
    console.error('❌ [前端调试] 网络响应:', error.response?.data)
    ElMessage.error('加载积分套餐失败')
  } finally {
    packagesLoading.value = false
  }
}

// 加载交易记录
const loadTransactionList = async () => {
  transactionsLoading.value = true
  try {
    const params = {
      current: transactionPagination.page,
      size: transactionPagination.size,
      userId: transactionSearch.userId,
      transactionType: transactionSearch.transactionType
    }
    
    const response = await getCreditsTransactions(params)
    if (response && response.success) {
      transactionList.value = response.data.records || []
      transactionPagination.total = response.data.total || 0
    } else {
      ElMessage.error('加载交易记录失败')
    }
  } catch (error) {
    ElMessage.error('加载交易记录失败')
    console.error(error)
  } finally {
    transactionsLoading.value = false
  }
}

// 加载消耗规则
const loadRuleList = async () => {
  rulesLoading.value = true
  try {
    const response = await getCreditsRules()
    if (response && response.success) {
      ruleList.value = response.data || []
    } else {
      ElMessage.error('加载消耗规则失败')
    }
  } catch (error) {
    ElMessage.error('加载消耗规则失败')
    console.error(error)
  } finally {
    rulesLoading.value = false
  }
}

// 新增套餐
const handleAddPackage = () => {
  Object.assign(packageForm, {
    id: null,
    name: '',
    creditsAmount: 0,
    price: 0,
    originalPrice: 0,
    discountLabel: '',
    isPopular: false,
    validityDays: 730,
    status: 1
  })
  packageDialogVisible.value = true
}

// 编辑套餐
const handleEditPackage = (row: any) => {
  console.log('编辑套餐原始数据:', row)
  // 确保数字类型的字段正确转换
  const formData = {
    id: row.id,
    name: row.name || '',
    creditsAmount: Number(row.creditsAmount) || 0,
    price: Number(row.price) || 0,
    originalPrice: Number(row.originalPrice) || 0,
    discountLabel: row.discountLabel || '',
    isPopular: Boolean(row.isPopular),
    validityDays: Number(row.validityDays) || 730,
    status: Number(row.status) || 1,
    sortOrder: Number(row.sortOrder) || 0
  }
  console.log('转换后的表单数据:', formData)
  Object.assign(packageForm, formData)
  packageDialogVisible.value = true
}

// 保存套餐
const handleSavePackage = async () => {
  if (!packageFormRef.value) return
  
  try {
    console.log('🔄 [编辑调试] 开始保存套餐...')
    console.log('🔄 [编辑调试] 当前表单数据:', JSON.stringify(packageForm, null, 2))
    
    await packageFormRef.value.validate()
    console.log('🔄 [编辑调试] 表单验证通过')
    
    packageSubmitting.value = true
    
    const isEdit = packageForm.id !== null
    console.log('🔄 [编辑调试] 操作类型:', isEdit ? '编辑' : '新增')
    console.log('🔄 [编辑调试] 套餐ID:', packageForm.id)
    
    const apiCall = isEdit 
      ? updateCreditsPackage(packageForm.id!, packageForm)
      : createCreditsPackage(packageForm)
    
    console.log('🔄 [编辑调试] 调用API:', isEdit ? 'updateCreditsPackage' : 'createCreditsPackage')
    
    const response = await apiCall
    
    console.log('🔄 [编辑调试] API响应:', response)
    console.log('🔄 [编辑调试] 响应状态:', response?.success)
    console.log('🔄 [编辑调试] 响应消息:', response?.message)
    
    if (response && response.success) {
      console.log('✅ [编辑调试] 操作成功')
      ElMessage.success(isEdit ? '更新成功' : '创建成功')
      packageDialogVisible.value = false
      console.log('🔄 [编辑调试] 重新加载套餐列表...')
      loadPackageList()
    } else {
      console.error('❌ [编辑调试] 操作失败:', response?.message)
      ElMessage.error(response?.message || '操作失败')
    }
  } catch (error: any) {
    console.error('❌ [编辑调试] 异常:', error)
    console.error('❌ [编辑调试] 错误详情:', error.message)
    console.error('❌ [编辑调试] 网络响应:', error.response?.data)
    ElMessage.error('操作失败')
  } finally {
    packageSubmitting.value = false
    console.log('🔄 [编辑调试] 保存操作完成')
  }
}

// 切换套餐状态
const handleTogglePackageStatus = async (row: any) => {
  const action = row.status === 1 ? '下架' : '上架'
  const newStatus = row.status === 1 ? 0 : 1
  
  try {
    await ElMessageBox.confirm(`确定要${action}此套餐吗？`, '确认操作')
    
    const response = await updateCreditsPackageStatus(row.id, newStatus)
    
    if (response && response.success) {
      ElMessage.success(`${action}成功`)
      loadPackageList()
    } else {
      ElMessage.error(response?.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 搜索交易记录
const handleSearchTransactions = () => {
  transactionPagination.page = 1
  loadTransactionList()
}

// 重置交易记录搜索
const handleResetTransactions = () => {
  transactionSearch.userId = ''
  transactionSearch.transactionType = ''
  transactionPagination.page = 1
  loadTransactionList()
}

// 交易记录分页
const handleTransactionSizeChange = (size: number) => {
  transactionPagination.size = size
  transactionPagination.page = 1
  loadTransactionList()
}

const handleTransactionCurrentChange = (page: number) => {
  transactionPagination.page = page
  loadTransactionList()
}

// 同步积分套餐到小程序数据库
const handleSyncPackagesToMiniProgram = async () => {
  try {
    await ElMessageBox.confirm('确定要同步积分套餐数据到小程序数据库吗？', '确认同步')
    
    const response = await syncCreditsPackagesToMiniProgram()
    
    if (response && response.success) {
      ElMessage.success('同步成功')
    } else {
      ElMessage.error(response?.message || '同步失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('同步失败')
    }
  }
}

// 同步积分消耗规则到小程序数据库
const handleSyncRulesToMiniProgram = async () => {
  try {
    await ElMessageBox.confirm('确定要同步积分消耗规则数据到小程序数据库吗？', '确认同步')
    
    const response = await syncCreditsRulesToMiniProgram()
    
    if (response && response.success) {
      ElMessage.success('同步成功')
    } else {
      ElMessage.error(response?.message || '同步失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('同步失败')
    }
  }
}

// 新增规则
const handleAddRule = () => {
  ElMessage.info('新增规则功能开发中...')
}

// 编辑规则
const handleEditRule = (row: any) => {
  ElMessage.info('编辑规则功能开发中...')
}

// 切换规则状态
const handleToggleRuleStatus = async (row: any) => {
  const action = row.status === 1 ? '禁用' : '启用'
  const newStatus = row.status === 1 ? 0 : 1
  
  try {
    await ElMessageBox.confirm(`确定要${action}此规则吗？`, '确认操作')
    
    const response = await updateCreditsRuleStatus(row.id, newStatus)
    
    if (response && response.success) {
      ElMessage.success(`${action}成功`)
      loadRuleList()
    } else {
      ElMessage.error(response?.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error(`${action}失败`)
    }
  }
}

// 工具函数
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const formatDate = (date: Date | string) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

const getTransactionTypeColor = (type: string) => {
  const colors: Record<string, string> = {
    purchase: 'success',
    consume: 'danger',
    earn: 'warning',
    refund: 'info'
  }
  return colors[type] || ''
}

const getTransactionTypeText = (type: string) => {
  const texts: Record<string, string> = {
    purchase: '购买',
    consume: '消费',
    earn: '获得',
    refund: '退款'
  }
  return texts[type] || type
}

const getSourceTypeText = (type: string) => {
  const texts: Record<string, string> = {
    credits_package: '积分套餐',
    ai_image: 'AI生图',
    ai_video: 'AI视频',
    hd_enhance: '高清增强',
    admin_add: '管理员添加'
  }
  return texts[type] || type
}

// 页面加载
onMounted(() => {
  loadStats()
  loadPackageList()
  loadTransactionList()
  loadRuleList()
})
</script>

<style scoped>
.credits-management {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.main-tabs {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.main-tabs :deep(.el-tabs__content) {
  margin-top: 16px;
}

.credits-amount {
  font-weight: 600;
  color: #f56c6c;
}

.amount-positive {
  color: #67c23a;
  font-weight: 600;
}

.amount-negative {
  color: #f56c6c;
  font-weight: 600;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.toolbar-buttons {
  display: flex;
  gap: 8px;
}
</style>
